package com.ssy.lingxi.marketing.serviceimpl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import com.ssy.lingxi.common.constant.marketing.ActivityTypeEnum;
import com.ssy.lingxi.common.constant.marketing.BelongTypeEnum;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.bo.MemberAndRoleIdBO;
import com.ssy.lingxi.common.model.dto.MemberAndRoleIdDTO;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.common.utils.DateTimeUtil;
import com.ssy.lingxi.marketing.api.model.response.TagDetailResp;
import com.ssy.lingxi.marketing.config.ServiceConfig;
import com.ssy.lingxi.marketing.entity.activity.ActivityGoodsDO;
import com.ssy.lingxi.marketing.entity.activity.ActivityGoodsSubsidiaryDO;
import com.ssy.lingxi.marketing.entity.activity.MerchantActivityDO;
import com.ssy.lingxi.marketing.entity.activity.PlatformActivityDO;
import com.ssy.lingxi.marketing.model.bo.*;
import com.ssy.lingxi.marketing.model.constant.ActivityGoodsAuditStatusEnum;
import com.ssy.lingxi.marketing.model.constant.ActivityStrPoolEnum;
import com.ssy.lingxi.marketing.model.constant.CommonBooleanEnum;
import com.ssy.lingxi.marketing.model.constant.GiveGiftTypeEnum;
import com.ssy.lingxi.marketing.model.dto.SubsidiaryDto;
import com.ssy.lingxi.marketing.model.vo.coupon.request.MobileActivityGoodsPageReq;
import com.ssy.lingxi.marketing.model.vo.coupon.request.MobileGoodsRelationTagReq;
import com.ssy.lingxi.marketing.model.vo.coupon.request.MobileProductDetailTagReq;
import com.ssy.lingxi.marketing.model.vo.coupon.request.MobileSetmealGoodsReq;
import com.ssy.lingxi.marketing.model.vo.coupon.response.*;
import com.ssy.lingxi.marketing.repository.ActivityGoodsRepository;
import com.ssy.lingxi.marketing.repository.ActivityGoodsSubsidiaryRepository;
import com.ssy.lingxi.marketing.repository.MerchantActivityRepository;
import com.ssy.lingxi.marketing.repository.PlatformActivityRepository;
import com.ssy.lingxi.marketing.service.IActivityGoodsCacheService;
import com.ssy.lingxi.marketing.service.ICouponReceiveService;
import com.ssy.lingxi.marketing.service.IMobileActivityGoodsService;
import com.ssy.lingxi.marketing.service.feign.IMemberFeignService;
import com.ssy.lingxi.marketing.service.feign.IProductFeignService;
import com.ssy.lingxi.marketing.service.feign.ISearchFeignService;
import com.ssy.lingxi.marketing.serviceimpl.base.activity.BaseActivityGoodsService;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityCheckRuleComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityGoodsTagAndPriceComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityQueryComponent;
import com.ssy.lingxi.marketing.serviceimpl.component.activity.ActivityTagComponent;
import com.ssy.lingxi.product.api.model.response.feign.CommodityPriceResponse;
import com.ssy.lingxi.search.api.model.request.TemplateCommoditySearchRequest;
import com.ssy.lingxi.search.api.model.response.CommoditySearchResponse;
import com.ssy.lingxi.search.api.model.response.CommoditySkuResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.persistence.criteria.Predicate;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 活动商品计算服务实现类
 *
 * @author yzc
 * @version 2.0.0
 * @date 2021/9/2
 */
@Slf4j
@Service
public class MobileActivityGoodsServiceImpl implements IMobileActivityGoodsService {

    @Resource
    private ActivityGoodsRepository activityGoodsRepository;
    @Resource
    private ActivityGoodsSubsidiaryRepository activityGoodsSubsidiaryRepository;
    @Resource
    private PlatformActivityRepository platformActivityRepository;
    @Resource
    private MerchantActivityRepository merchantActivityRepository;
    @Resource
    private ICouponReceiveService couponCalculateService;
    @Resource
    private ActivityQueryComponent activityQueryComponent;
    @Resource
    private ActivityGoodsTagAndPriceComponent activityGoodsTagAndPriceComponent;
    @Resource
    private ActivityTagComponent activityTagComponent;
    @Resource
    private IProductFeignService productFeignService;
    @Resource
    private ActivityCheckRuleComponent activityCheckRuleComponent;
    @Resource
    private IActivityGoodsCacheService activityGoodsCacheService;
    @Resource
    private BaseActivityGoodsService goodsService;
    @Resource
    private ISearchFeignService searchFeignService;
    @Resource
    private IMemberFeignService memberFeignService;

    /**
     * 判断秒杀是否最后一期结束了
     *
     * @param secKillStartTime
     * @param secKillEndTime
     * @param activityEndTime
     * @return
     */
    private boolean isLastSecKillOver(Long secKillStartTime, Long secKillEndTime, Long activityEndTime) {
        //如果当前时间处理结束时段与活动结束之间，则秒杀活动也算结束了
        DateTime killStart = DateUtil.date(secKillStartTime);
        DateTime killEnd = DateUtil.date(secKillEndTime);
        DateTime now = DateTime.now();
        String today = DateUtil.formatDate(now);
        String startTime = DateUtil.formatTime(killStart);
        String endTime = DateUtil.formatTime(killEnd);
        DateTime killStartToday = DateUtil.parseDateTime(today + " " + startTime);
        DateTime killEndToday = DateUtil.parseDateTime(today + " " + endTime);
        //当前时间大于秒杀今天结束时段，并且秒杀今天开始时段+1天大于活动结束时间，则秒杀结束了
        return now.compareTo(killEndToday) >= 0 && DateUtil.offsetDay(killStartToday, 1).compareTo(DateUtil.date(activityEndTime)) >= 0;
    }

    /**
     * 查询单个会员的店铺权益
     * @param loginUser
     * @param upperMember
     * @return
     */
    private Double getMemberLevelRight(MemberAndRoleIdBO loginUser,MemberAndRoleIdDTO upperMember){
        if(loginUser==null||upperMember==null){return 1D;}
        List<MemberAndRoleIdDTO> dtoList=Collections.singletonList(upperMember);
        Map<String, Double> memberPriceRight = memberFeignService.getMemberPriceRight(loginUser.getMemberId(), loginUser.getRoleId(), dtoList);
        if(!memberPriceRight.isEmpty()){
            return memberPriceRight.values().stream().findFirst().get();
        }
        return 1D;
    }

    @Override
    public Wrapper<MobileProductDetailTagResp> getActivityGoodsProductDetailTag(UserLoginCacheDTO loginUser, MobileProductDetailTagReq request) {
        MemberAndRoleIdBO memberAndRoleIdBO = null;
        if (Objects.nonNull(loginUser)) {
            memberAndRoleIdBO = new MemberAndRoleIdBO(loginUser.getMemberId(), loginUser.getMemberRoleId());
        }

        // skuId
        Long skuId = request.getSkuId();

        // 活动商品
        List<ActivityGoodsDetailBO> activityGoodsBOList = activityQueryComponent.selectCheckActivityExecutingGoodsByProductSku(memberAndRoleIdBO, request.getShopId(), request.getProductId(), request.getSkuId());

        //搜索页查询详情，过滤掉拼团活动（拼团只能在活动页进入）
        if (request.getFilterGroup() != null && request.getFilterGroup() && CollectionUtil.isNotEmpty(activityGoodsBOList)) {
            activityGoodsBOList = activityGoodsBOList.stream().filter(o -> !(ActivityTypeEnum.GROUP_PURCHASE.getCode().equals(o.getActivityBO().getActivityType()))).collect(Collectors.toList());
        }

        MobileProductDetailTagResp productDetailTagResp = new MobileProductDetailTagResp();

        // 处理活动商品
        List<TagDetailResp> tagDetailRespList = new ArrayList<>();
        List<String> tagList = new ArrayList<>();

        List<ActivityGoodsSkuBO> goodsSkuBOList = activityGoodsTagAndPriceComponent.handSkuTag(activityGoodsBOList);
        // 最优惠的sku
        Optional<ActivityGoodsSkuBO> preferentialGoodsSkuOptional = goodsSkuBOList.stream().min(Comparator.comparing(ActivityGoodsSkuBO::getSkuPreferentialPrice));
        if (preferentialGoodsSkuOptional.isPresent()) {
            ActivityGoodsSkuBO preferentialGoodsSkuBO = preferentialGoodsSkuOptional.get();
            Boolean iskillTime = null;
            for (ActivityGoodsTagBO tagBO : preferentialGoodsSkuBO.getTagList()) {
                TagDetailResp tagDetailResp = new TagDetailResp();
                tagDetailResp.setActivityId(tagBO.getActivityId());
                tagDetailResp.setBelongType(tagBO.getBelongType());
                tagDetailResp.setActivityType(tagBO.getActivityType());
                tagDetailResp.setStartTime(tagBO.getStartTime());
                tagDetailResp.setEndTime(tagBO.getEndTime());
                tagDetailResp.setPreferentialTag(tagBO.getPreferentialTag());
                tagDetailResp.setPreferentialTagDesc(tagBO.getPreferentialTagDesc());
                // 是否可用优惠券
                tagDetailResp.setCanUesCoupon(activityCheckRuleComponent.checkGoodsTagCanUserCoupon(Collections.singletonList(tagBO)) ? CommonBooleanEnum.YES.getCode() : CommonBooleanEnum.NO.getCode());
                // 赠送促销
                if (ActivityTypeEnum.GIVE.getCode().equals(tagBO.getActivityType())) {
                    GiveBO giveBO = (GiveBO) tagBO.getActivityDefinedBO();
                    if (GiveGiftTypeEnum.COUPON.getCode().equals(giveBO.getGiftType())) {
                        // 赠送优惠券不可跳转
                        tagDetailResp.setJumpToProductPage(CommonBooleanEnum.NO.getCode());
                        tagDetailResp.setConcreteType(10);
                    } else {
                        // 赠送商品可跳转
                        tagDetailResp.setJumpToProductPage(CommonBooleanEnum.YES.getCode());
                        tagDetailResp.setConcreteType(9);
                    }
                    //添加梯度
                    if (Objects.nonNull(loginUser)) {
                        tagDetailResp.setLadders(activityGoodsTagAndPriceComponent.buildLadders(ActivityTypeEnum.GIVE.getCode(), tagBO.getActivityDefinedBO(), tagBO.getActivityGoodsId(), loginUser.getMemberId(), loginUser.getMemberRoleId(), request.getShopId()));
                    }
                } else {
                    // 其他活动都可跳转
                    tagDetailResp.setJumpToProductPage(CommonBooleanEnum.YES.getCode());
                }

                // 秒杀
                if (ActivityTypeEnum.SEC_KILL.getCode().equals(tagBO.getActivityType())) {
                    SecKillBO secKillBO = (SecKillBO) tagBO.getActivityDefinedBO();
                    iskillTime = DateTimeUtil.isBelongPeriodOfNow(secKillBO.getStartTime(), secKillBO.getEndTime());
                    //判断是否存在秒杀最后一期结束
                    if (isLastSecKillOver(secKillBO.getStartTime(), secKillBO.getEndTime(), tagBO.getEndTime())) {
                        continue;
                    } else {
                        // 活动结束时间
                        productDetailTagResp.setSeckillStartTime(secKillBO.getStartTime());
                        productDetailTagResp.setSeckillEndTime(secKillBO.getEndTime());
                    }
                    //秒杀详情页与进货单页面标签不一致
                    tagDetailResp.setPreferentialTagDesc(StrFormatter.format(ActivityStrPoolEnum.secKill_ptd.getMessage(), DateUtil.format(new Date(tagBO.getEndTime()), DatePattern.NORM_DATETIME_FORMAT)));
                }

                tagList.add(tagBO.getActivityTypeTag());
                tagDetailRespList.add(tagDetailResp);
            }

            // 是否可用优惠券
            productDetailTagResp.setCanUseCoupon(preferentialGoodsSkuBO.getCanUesCoupon());
            productDetailTagResp.setPreferentialSkuId(preferentialGoodsSkuBO.getSkuId());
            productDetailTagResp.setPromotionPrice(preferentialGoodsSkuBO.getPromotionPrice());
            //非秒杀时段，不显示秒杀价（秒杀非叠加适应）
            BigDecimal preferentialPrice = (iskillTime != null && !iskillTime) ? null : preferentialGoodsSkuBO.getSkuPreferentialPrice();
            productDetailTagResp.setPreferentialPrice(preferentialPrice);
            //如果为 特价、直降、折扣，到手价*会员折扣
            if(BigDecimal.ZERO.compareTo(productDetailTagResp.getPromotionPrice())<0&&Objects.nonNull(loginUser)){
                //查询商品可否使用会员折扣
                Map<Long, CommodityPriceResponse> memberLRC = productFeignService.getCommodityPriceAndMemberPriceBatch(request.getShopId(), request.getCommodityType(), loginUser.getMemberId(), loginUser.getMemberRoleId(), Collections.singletonList(skuId));
                if(memberLRC!=null&&memberLRC.get(skuId).getIsMemberPrice()) {
                    //查询会员权益
                    Double memberLevelRight = getMemberLevelRight(memberAndRoleIdBO, new MemberAndRoleIdDTO(request.getMemberId(), request.getRoleId()));
                    BigDecimal lrs = BigDecimal.valueOf(memberLevelRight);
                    productDetailTagResp.setPromotionPrice(lrs.multiply(productDetailTagResp.getPromotionPrice()));
                    productDetailTagResp.setPreferentialPrice(lrs.multiply(productDetailTagResp.getPreferentialPrice()));
                }
            }
            // 最优惠的sku(优惠券查询)
            skuId = preferentialGoodsSkuBO.getSkuId();
        }

        productDetailTagResp.setTagList(tagList);
        productDetailTagResp.setTagDetailList(tagDetailRespList);

        // 平台优惠券
        List<MobileCouponResponse> platformCouponList = new ArrayList<>();
        Wrapper<List<MobileCouponResponse>> platformCouponWrapper = couponCalculateService.listPlatformCouponCanReceiveComplete(loginUser, request.getShopId());
        if (ResponseCode.SUCCESS.getCode() == platformCouponWrapper.getCode()) {
            if (!CollectionUtils.isEmpty(platformCouponWrapper.getData())) {
                platformCouponList = platformCouponWrapper.getData();
            }
        }


        // 商家优惠券
        List<MobileCouponResponse> merchantCouponList = new ArrayList<>();
        Wrapper<List<MobileCouponResponse>> merchantCouponWrapper = couponCalculateService.listGoodsMerchantCoupon(loginUser, request.getShopId(), request.getMemberId(), request.getRoleId(), skuId, request.getCategoryId(), request.getBrandId());
        if (ResponseCode.SUCCESS.getCode() == merchantCouponWrapper.getCode()) {
            if (!CollectionUtils.isEmpty(merchantCouponWrapper.getData())) {
                merchantCouponList = merchantCouponWrapper.getData();
            }
        }

        platformCouponList.addAll(merchantCouponList);
        //如果存在优惠券，且未参与活动，则可用券
        if(platformCouponList.size()>0&&productDetailTagResp.getCanUseCoupon()==null){
            productDetailTagResp.setCanUseCoupon(CommonBooleanEnum.YES.getCode());
        }
        productDetailTagResp.setCouponList(platformCouponList);

        return Wrapper.success(productDetailTagResp);
    }

    @Override
    public Wrapper<MobileGoodsRelationTagResp> getActivityRelationGoods(UserLoginCacheDTO loginUser, MobileGoodsRelationTagReq request) {
        ActivityBO activityBO = new ActivityBO();
        List<Long> productIds = new ArrayList<>();

        List<ActivityGoodsDetailBO> activityGoodsDetailBOLists = new ArrayList<>();

        if (BelongTypeEnum.PLATFORM.getCode().equals(request.getBelongType())) {
            PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getActivityId()).orElse(null);
            if (Objects.isNull(platformActivityDO)) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
            }

            activityBO.setActivityId(platformActivityDO.getId());
            activityBO.setBelongType(BelongTypeEnum.PLATFORM.getCode());
            activityBO.setActivityType(platformActivityDO.getActivityType());
            activityBO.setActivityName(platformActivityDO.getActivityName());
            activityBO.setStartTime(platformActivityDO.getStartTime());
            activityBO.setEndTime(platformActivityDO.getEndTime());
            activityBO.setActivityDefined(platformActivityDO.getActivityDefined());
            activityBO.setMemberId(platformActivityDO.getMemberId());
            activityBO.setRoleId(platformActivityDO.getRoleId());


            if (ActivityTypeEnum.GIVE.getCode().equals(platformActivityDO.getActivityType())) {
                // 赠品
                GiveBO giveBO = (GiveBO) platformActivityDO.getActivityDefined();
                // 赠送类型为赠商品
                if (GiveGiftTypeEnum.GOODS.getCode().equals(giveBO.getGiftType())) {
                    productIds = this.selectGoodsSubsidiary(BelongTypeEnum.PLATFORM, request.getActivityId(), request.getSkuId(), request.getProductName());
                }
            } else if (ActivityTypeEnum.SWAP.getCode().equals(platformActivityDO.getActivityType())) {
                // 换购
                productIds = this.selectGoodsSubsidiary(BelongTypeEnum.PLATFORM, request.getActivityId(), request.getSkuId(), request.getProductName());
            } else {
                productIds = this.selectActivityGoods(BelongTypeEnum.PLATFORM, request.getActivityId(), request.getProductName());
                activityGoodsDetailBOLists = activityQueryComponent.selectPlatformActivityExecutingByProductAndActivity(request.getShopId(), productIds, null);
            }
        } else if (BelongTypeEnum.MERCHANT.getCode().equals(request.getBelongType())) {
            MerchantActivityDO merchantActivityDO = merchantActivityRepository.findById(request.getActivityId()).orElse(null);
            if (Objects.isNull(merchantActivityDO)) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
            }

            activityBO.setActivityId(merchantActivityDO.getId());
            activityBO.setBelongType(BelongTypeEnum.MERCHANT.getCode());
            activityBO.setActivityType(merchantActivityDO.getActivityType());
            activityBO.setActivityName(merchantActivityDO.getActivityName());
            activityBO.setStartTime(merchantActivityDO.getStartTime());
            activityBO.setEndTime(merchantActivityDO.getEndTime());
            activityBO.setActivityDefined(merchantActivityDO.getActivityDefined());
            activityBO.setMemberId(merchantActivityDO.getMemberId());
            activityBO.setRoleId(merchantActivityDO.getRoleId());

            if (ActivityTypeEnum.GIVE.getCode().equals(merchantActivityDO.getActivityType())) {
                // 赠送
                GiveBO giveBO = (GiveBO) merchantActivityDO.getActivityDefined();
                if (GiveGiftTypeEnum.GOODS.getCode().equals(giveBO.getGiftType())) {
                    productIds = this.selectGoodsSubsidiary(BelongTypeEnum.MERCHANT, request.getActivityId(), request.getSkuId(), request.getProductName());
                }
            } else if (ActivityTypeEnum.SWAP.getCode().equals(merchantActivityDO.getActivityType())) {
                // 换购
                productIds = this.selectGoodsSubsidiary(BelongTypeEnum.MERCHANT, request.getActivityId(), request.getSkuId(), request.getProductName());
            } else {
                productIds = this.selectActivityGoods(BelongTypeEnum.MERCHANT, request.getActivityId(), request.getProductName());
                activityGoodsDetailBOLists = activityQueryComponent.selectMerchantActivityExecutingByProductAndActivity(request.getShopId(), productIds, null);
            }
        }

        // 查询活动信息
        ActivityTagBO activityTagBO = activityTagComponent.handActivityTag(activityBO);

        // 返回结果
        MobileGoodsRelationTagResp mobileGoodsRelationTagResp = new MobileGoodsRelationTagResp();
        mobileGoodsRelationTagResp.setActivityId(activityTagBO.getActivityId());
        mobileGoodsRelationTagResp.setBelongType(activityTagBO.getBelongType());
        mobileGoodsRelationTagResp.setActivityType(activityTagBO.getActivityType());
        mobileGoodsRelationTagResp.setActivityName(activityTagBO.getActivityName());
        mobileGoodsRelationTagResp.setStartTime(activityTagBO.getStartTime());
        mobileGoodsRelationTagResp.setEndTime(activityTagBO.getEndTime());
        mobileGoodsRelationTagResp.setActivityDescription(activityTagBO.getActivityDescription());

        // 无商品查询直接返回结果
        if (CollectionUtils.isEmpty(productIds)) {
            // 返回商品信息
            mobileGoodsRelationTagResp.setCommodityList(Collections.emptyList());
            return Wrapper.success(mobileGoodsRelationTagResp);
        }

        // 活动商品标签
        List<ActivityGoodsProductBO> productTagList = activityGoodsTagAndPriceComponent.handProductTag(activityGoodsDetailBOLists);

        // 查询商品信息和填充活动标签
        Wrapper<List<MobileActivityRelationGoodsResp>> listWrapper = this.queryGoodsInfoAndFillTag(request.getShopId(), productIds, productTagList, request.getProvinceCode(), request.getCityCode());
        if (ResponseCode.SUCCESS.getCode() != listWrapper.getCode()) {
            return Wrapper.fail(listWrapper.getCode(), listWrapper.getMessage());
        }

        // 返回商品信息
        mobileGoodsRelationTagResp.setCommodityList(Optional.ofNullable(listWrapper.getData()).orElse(Collections.emptyList()));

        return Wrapper.success(mobileGoodsRelationTagResp);
    }

    private List<MobileActivityRelationGoodsResp> buildMobileActivityRelationGoodsRespList(List<ActivityGoodsSubsidiaryDO> subsidiaryDOS) {
        if (CollectionUtil.isEmpty(subsidiaryDOS)) {
            return null;
        }
        return subsidiaryDOS.stream().map(o -> {
            MobileActivityRelationGoodsResp resp = new MobileActivityRelationGoodsResp();
            resp.setMainPic(o.getProductImgUrl());
            resp.setSkuId(o.getSkuId());
            resp.setProductId(o.getProductId());
            resp.setProductName(o.getProductName());
            resp.setMemberId(o.getMemberId());
            resp.setMemberRoleId(o.getRoleId());
            resp.setUnitName(o.getUnit());
            //resp.setPriceType();
            resp.setLimitValue(o.getLimitValue());
            resp.setOriginalPrice(o.getPrice());
            BigDecimal price = o.getSwapPrice() == null ? o.getPrice() : o.getSwapPrice();
            resp.setPrice(price);
            //resp.setMemberName();
            return resp;
        }).collect(Collectors.toList());
    }

    private List<MobileActivityRelationGoodsResp> buildMobileActivityRelationGoodsRespList(Integer belongType, Long activityId, String productName) {
        List<ActivityGoodsDO> activityGoodsDOList = goodsService.getActivityGoodsDOList(belongType, activityId, productName);
        if (CollectionUtil.isEmpty(activityGoodsDOList)) {
            return null;
        }
        return activityGoodsDOList.stream().map(o -> {
            MobileActivityRelationGoodsResp resp = new MobileActivityRelationGoodsResp();
            resp.setMainPic(o.getProductImgUrl());
            resp.setSkuId(o.getSkuId());
            resp.setProductId(o.getProductId());
            resp.setProductName(o.getProductName());
            resp.setMemberId(o.getMemberId());
            resp.setMemberRoleId(o.getRoleId());
            resp.setUnitName(o.getUnit());
            //resp.setPriceType();
            BigDecimal price = o.getActivityPrice();
            resp.setPrice(price);
            //resp.setMemberName();
            return resp;
        }).collect(Collectors.toList());
    }

    private MobileActivityRelationGoodsResp buildMainGoodsInfo(Integer belongType, Long activityId, Long skuId) {
        ActivityGoodsDO mainSkuInfo = activityGoodsRepository.findAllByBelongTypeAndActivityIdAndSkuId(belongType, activityId, skuId);
        MobileActivityRelationGoodsResp mainGoods = new MobileActivityRelationGoodsResp();
        mainGoods.setMainPic(mainSkuInfo.getProductImgUrl());
        mainGoods.setProductName(mainSkuInfo.getProductName());
        mainGoods.setPrice(mainSkuInfo.getPrice());
        mainGoods.setOriginalPrice(mainSkuInfo.getPrice());
        mainGoods.setUnitName(mainSkuInfo.getUnit());
        mainGoods.setProductId(mainSkuInfo.getProductId());
        mainGoods.setSkuId(mainSkuInfo.getSkuId());
        mainGoods.setMemberId(mainSkuInfo.getMemberId());
        mainGoods.setMemberRoleId(mainSkuInfo.getRoleId());
        return mainGoods;
    }

    @Override
    public Wrapper<MobileGoodsRelationTagResp> getActivityRelationGoodsList(UserLoginCacheDTO loginUser, MobileGoodsRelationTagReq request) {
        ActivityBO activityBO = new ActivityBO();
        List<MobileActivityRelationGoodsResp> productIds = null;
        List<ActivityGoodsDetailBO> activityGoodsDetailBOS = null;
        List<ActivityGoodsDetailBO> activityGoodsDetailBOLists = new ArrayList<>();
        MobileActivityRelationGoodsResp mainGoods = null;
        Integer swapType = null;
        if (BelongTypeEnum.PLATFORM.getCode().equals(request.getBelongType())) {
            PlatformActivityDO platformActivityDO = platformActivityRepository.findById(request.getActivityId()).orElse(null);
            if (Objects.isNull(platformActivityDO)) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
            }
            activityBO.setActivityId(platformActivityDO.getId());
            activityBO.setBelongType(BelongTypeEnum.PLATFORM.getCode());
            activityBO.setActivityType(platformActivityDO.getActivityType());
            activityBO.setActivityName(platformActivityDO.getActivityName());
            activityBO.setStartTime(platformActivityDO.getStartTime());
            activityBO.setEndTime(platformActivityDO.getEndTime());
            activityBO.setActivityDefined(platformActivityDO.getActivityDefined());
            activityBO.setMemberId(platformActivityDO.getMemberId());
            activityBO.setRoleId(platformActivityDO.getRoleId());


            if (ActivityTypeEnum.GIVE.getCode().equals(platformActivityDO.getActivityType())) {
                // 赠品
                GiveBO giveBO = (GiveBO) platformActivityDO.getActivityDefined();
                // 赠送类型为赠商品
                if (GiveGiftTypeEnum.GOODS.getCode().equals(giveBO.getGiftType())) {
                    productIds = getMobileActivityRelationGoodsRespList(BelongTypeEnum.PLATFORM, request.getActivityId(), request.getSkuId(), request.getProductName());
                }
            } else if (ActivityTypeEnum.SWAP.getCode().equals(platformActivityDO.getActivityType())) {
                // 换购
                productIds = getMobileActivityRelationGoodsRespList(BelongTypeEnum.PLATFORM, request.getActivityId(), request.getSkuId(), request.getProductName());
                //主商品信息查询
                mainGoods = buildMainGoodsInfo(BelongTypeEnum.PLATFORM.getCode(), request.getActivityId(), request.getSkuId());
                SwapBO swapBO = (SwapBO) platformActivityDO.getActivityDefined();
                swapType = swapBO.getSwapType();
            } else {
                productIds = buildMobileActivityRelationGoodsRespList(BelongTypeEnum.PLATFORM.getCode(), request.getActivityId(), request.getProductName());
                List<Long> skuIds = productIds.stream().map(o -> o.getSkuId()).collect(Collectors.toList());
                activityGoodsDetailBOS = activityQueryComponent.selectPlatformActivityExecuting(request.getShopId(), null, skuIds, request.getActivityId());

            }
        } else if (BelongTypeEnum.MERCHANT.getCode().equals(request.getBelongType())) {
            MerchantActivityDO merchantActivityDO = merchantActivityRepository.findById(request.getActivityId()).orElse(null);
            if (Objects.isNull(merchantActivityDO)) {
                return Wrapper.fail(ResponseCode.MARKETING_ACTIVITY_NOT_EXISTS);
            }
            activityBO.setActivityId(merchantActivityDO.getId());
            activityBO.setBelongType(BelongTypeEnum.MERCHANT.getCode());
            activityBO.setActivityType(merchantActivityDO.getActivityType());
            activityBO.setActivityName(merchantActivityDO.getActivityName());
            activityBO.setStartTime(merchantActivityDO.getStartTime());
            activityBO.setEndTime(merchantActivityDO.getEndTime());
            activityBO.setActivityDefined(merchantActivityDO.getActivityDefined());
            activityBO.setMemberId(merchantActivityDO.getMemberId());
            activityBO.setRoleId(merchantActivityDO.getRoleId());

            if (ActivityTypeEnum.GIVE.getCode().equals(merchantActivityDO.getActivityType())) {
                // 赠送
                GiveBO giveBO = (GiveBO) merchantActivityDO.getActivityDefined();
                if (GiveGiftTypeEnum.GOODS.getCode().equals(giveBO.getGiftType())) {
                    productIds = getMobileActivityRelationGoodsRespList(BelongTypeEnum.MERCHANT, request.getActivityId(), request.getSkuId(), request.getProductName());
                }
            } else if (ActivityTypeEnum.SWAP.getCode().equals(merchantActivityDO.getActivityType())) {
                // 换购
                productIds = getMobileActivityRelationGoodsRespList(BelongTypeEnum.MERCHANT, request.getActivityId(), request.getSkuId(), request.getProductName());
                //主商品信息查询
                mainGoods = buildMainGoodsInfo(BelongTypeEnum.MERCHANT.getCode(), request.getActivityId(), request.getSkuId());
                SwapBO swapBO = (SwapBO) merchantActivityDO.getActivityDefined();
                swapType = swapBO.getSwapType();
            } else {
                productIds = buildMobileActivityRelationGoodsRespList(BelongTypeEnum.MERCHANT.getCode(), request.getActivityId(), request.getProductName());
                List<Long> skuIds = productIds.stream().map(o -> o.getSkuId()).collect(Collectors.toList());
                activityGoodsDetailBOS = activityQueryComponent.selectMerchantActivityExecuting(request.getShopId(), null, skuIds, request.getActivityId());
            }
        }

        // 查询活动信息
        ActivityTagBO activityTagBO = activityTagComponent.handActivityTag(activityBO);

        // 返回结果
        MobileGoodsRelationTagResp mobileGoodsRelationTagResp = new MobileGoodsRelationTagResp();
        mobileGoodsRelationTagResp.setActivityId(activityTagBO.getActivityId());
        mobileGoodsRelationTagResp.setBelongType(activityTagBO.getBelongType());
        mobileGoodsRelationTagResp.setActivityType(activityTagBO.getActivityType());
        mobileGoodsRelationTagResp.setActivityName(activityTagBO.getActivityName());
        mobileGoodsRelationTagResp.setStartTime(activityTagBO.getStartTime());
        mobileGoodsRelationTagResp.setEndTime(activityTagBO.getEndTime());
        mobileGoodsRelationTagResp.setActivityDescription(activityTagBO.getActivityDescription());
        mobileGoodsRelationTagResp.setMainGoods(mainGoods);
        mobileGoodsRelationTagResp.setSwapType(swapType);
        // 无商品查询直接返回结果
        if (CollectionUtils.isEmpty(productIds)) {
            // 返回商品信息
            mobileGoodsRelationTagResp.setCommodityList(Collections.emptyList());
            return Wrapper.success(mobileGoodsRelationTagResp);
        }
        List<ActivityGoodsSkuBO> activityGoodsSkuBOS = activityGoodsTagAndPriceComponent.handSkuTag(activityGoodsDetailBOS);
        Map<Long, ActivityGoodsSkuBO> goodsSkuBOMap = activityGoodsSkuBOS.stream().collect(Collectors.toMap(ActivityGoodsSkuBO::getSkuId, v -> v, (v1, v2) -> v1));
        // 活动商品标签与价格
        for (MobileActivityRelationGoodsResp resp : productIds) {
            if (goodsSkuBOMap != null) {
                ActivityGoodsSkuBO activityGoodsSkuBO = goodsSkuBOMap.get(resp.getSkuId());
                if (activityGoodsSkuBO != null) {
                    if (CollectionUtil.isNotEmpty(activityGoodsSkuBO.getTagList())) {
                        resp.setTagList(activityGoodsSkuBO.getTagList().stream().map(o -> o.getActivityTypeTag()).distinct().collect(Collectors.toList()));
                    }
                    resp.setPrice(activityGoodsSkuBO.getSkuPreferentialPrice());
                    resp.setOriginalPrice(activityGoodsSkuBO.getPromotionPrice());
                }
            }
        }
        //查询商品服务获得销量与价格
        List<Long> skuIds = new ArrayList<>(goodsSkuBOMap.keySet());
        if (mainGoods != null) {
            skuIds.add(mainGoods.getSkuId());
            //增加换购商品的查询
            skuIds.addAll(productIds.stream().map(o ->o.getSkuId()).collect(Collectors.toList()));
        }
        Map<Long, CommoditySkuResponse> commoditySkuMap = searchFeignService.getCommoditySkuMap(request.getShopId(), skuIds, loginUser != null ? loginUser.getMemberId() : null, loginUser != null ? loginUser.getMemberRoleId() : null, request.getProvinceCode(), request.getCityCode());
        if (commoditySkuMap != null) {
            //筛选商品
            productIds = productIds.stream().filter(p -> commoditySkuMap.get(p.getSkuId()) != null).collect(Collectors.toList());
            productIds.forEach(resp -> {
                CommoditySkuResponse skuInfo = commoditySkuMap.get(resp.getSkuId());
                if (skuInfo != null) {
                    resp.setSlogan(skuInfo.getSlogan());
                    String[] sellingPoint = skuInfo.getSellingPoint();
                    if (sellingPoint != null) {
                        resp.setSellingPoint(Arrays.asList(sellingPoint));
                    }
                    resp.setSold(skuInfo.getSold());
                    resp.setPriceType(skuInfo.getPriceType());
                }
            });
            if (mainGoods != null) {
                CommoditySkuResponse skuInfo = commoditySkuMap.get(mainGoods.getSkuId());
                if (skuInfo != null) {
                    mainGoods.setSlogan(skuInfo.getSlogan());
                    String[] sellingPoint = skuInfo.getSellingPoint();
                    if (sellingPoint != null) {
                        mainGoods.setSellingPoint(Arrays.asList(sellingPoint));
                    }
                    mainGoods.setSold(skuInfo.getSold());
                    mainGoods.setPriceType(skuInfo.getPriceType());
                }
            }
            // 返回商品信息
            mobileGoodsRelationTagResp.setCommodityList(productIds);
        } else {
            // 返回商品信息
            mobileGoodsRelationTagResp.setCommodityList(Collections.emptyList());
        }
        return Wrapper.success(mobileGoodsRelationTagResp);
    }

    /**
     * 查询商品信息和填充活动标签
     *
     * @param productIds     商品id
     * @param productTagList 商品的活动标签
     * @return 返回结果
     */
    private Wrapper<List<MobileActivityRelationGoodsResp>> queryGoodsInfoAndFillTag(Long shopId, List<Long> productIds, List<ActivityGoodsProductBO> productTagList, String provinceCode, String cityCode) {
        // productId - ActivityGoodsProductBO
        Map<Long, ActivityGoodsProductBO> productTagMap = productTagList.stream().collect(Collectors.toMap(ActivityGoodsProductBO::getProductId, e -> e, (e1, e2) -> e2));

        // 查询商品信息
        TemplateCommoditySearchRequest templateCommoditySearchRequest = new TemplateCommoditySearchRequest();
        // **没有提供查全部的接口, 所以传分页参数查全部**
        templateCommoditySearchRequest.setCurrent(1);
        templateCommoditySearchRequest.setPageSize(9999);
        templateCommoditySearchRequest.setShopId(shopId);
        templateCommoditySearchRequest.setIdInList(productIds);
        templateCommoditySearchRequest.setProvinceCode(provinceCode);
        templateCommoditySearchRequest.setCityCode(cityCode);
        Wrapper<PageData<CommoditySearchResponse>> pageDataWrapper = productFeignService.searchCommodityList(templateCommoditySearchRequest);
        if (ResponseCode.SUCCESS.getCode() != pageDataWrapper.getCode()) {
            return Wrapper.fail(pageDataWrapper.getCode(), pageDataWrapper.getMessage());
        }

        List<CommoditySearchResponse> templateResponses = Optional.ofNullable(pageDataWrapper.getData().getData()).orElse(new ArrayList<>());
        List<MobileActivityRelationGoodsResp> goodsList = new ArrayList<>();
        for (CommoditySearchResponse response : templateResponses) {
            MobileActivityRelationGoodsResp goods = new MobileActivityRelationGoodsResp();
            goods.setProductId(response.getId());
            goods.setMainPic(response.getMainPic());
            goods.setProductName(response.getName());
            BigDecimal price = CollectionUtils.isEmpty(productTagList) ? BigDecimal.valueOf(response.getMin()) : Optional.ofNullable(productTagMap.get(response.getId())).map(ActivityGoodsProductBO::getProductPreferentialPrice).orElse(BigDecimal.ZERO);
            goods.setPrice(price);
            goods.setUnitName(response.getUnitName());
            goods.setPriceType(response.getPriceType());
            goods.setSlogan(response.getSlogan());
            goods.setSellingPoint(ObjectUtils.isEmpty(response.getSellingPoint()) ? Collections.emptyList() : Arrays.asList(response.getSellingPoint()));
            goods.setMemberId(response.getMemberId());
            goods.setMemberRoleId(response.getMemberRoleId());
            goods.setMemberName(response.getMemberName());
            goods.setStoreId(response.getStoreId());
            goods.setStoreName(response.getStoreName());
            goods.setSold(response.getSold());
            String tag = CollectionUtils.isEmpty(productTagList) ? "" : Optional.ofNullable(productTagMap.get(response.getId())).map(e -> e.getTotalTagList().stream().findFirst().map(ActivityGoodsTagBO::getActivityTypeTag).orElse("")).orElse("");
            goods.setTagList(Collections.singletonList(tag));

            goodsList.add(goods);
        }

        return Wrapper.success(goodsList);
    }

    private List<ActivityGoodsSubsidiaryDO> getActivityGoodsSubsidiaryDOList(BelongTypeEnum belongTypeEnum, Long activityId, Long skuId, String productName) {
        // 赠送和换购显示附属商品
        ActivityGoodsDO activityGoodsDO = activityGoodsRepository.findAllByBelongTypeAndActivityIdAndSkuId(belongTypeEnum.getCode(), activityId, skuId);
        if (Objects.isNull(activityGoodsDO)) {
            throw new BusinessException(ResponseCode.MARKETING_RECORDS_DONT_EXIST);
        }

        List<ActivityGoodsSubsidiaryDO> activityGoodsSubsidiaryDOList = activityGoodsSubsidiaryRepository.findAll((Specification<ActivityGoodsSubsidiaryDO>) (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            predicateList.add(cb.equal(root.get("activityGoods").get("id"), activityGoodsDO.getId()));

            if (StringUtils.hasLength(productName)) {
                predicateList.add(cb.like(root.get("productName"), "%" + productName + "%"));
            }

            Predicate[] p = new Predicate[predicateList.size()];
            return query.where(predicateList.toArray(p)).getRestriction();
        });
        return activityGoodsSubsidiaryDOList;
    }

    private List<MobileActivityRelationGoodsResp> getMobileActivityRelationGoodsRespList(BelongTypeEnum belongTypeEnum, Long activityId, Long skuId, String productName) {
        List<ActivityGoodsSubsidiaryDO> activityGoodsSubsidiaryDOList = getActivityGoodsSubsidiaryDOList(belongTypeEnum, activityId, skuId, productName);
        return buildMobileActivityRelationGoodsRespList(activityGoodsSubsidiaryDOList);
    }

    private List<Long> selectGoodsSubsidiary(BelongTypeEnum belongTypeEnum, Long activityId, Long skuId, String productName) {
        // 赠送和换购显示附属商品
        List<ActivityGoodsSubsidiaryDO> activityGoodsSubsidiaryDOList = getActivityGoodsSubsidiaryDOList(belongTypeEnum, activityId, skuId, productName);
        return activityGoodsSubsidiaryDOList.stream().map(ActivityGoodsSubsidiaryDO::getProductId).distinct().collect(Collectors.toList());
    }

    private List<Long> selectActivityGoods(BelongTypeEnum belongTypeEnum, Long activityId, String productName) {
        // 其他活动显示该活动所有参与商品
        List<ActivityGoodsDO> activityGoodsDOList = activityGoodsRepository.findAll((Specification<ActivityGoodsDO>) (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            predicateList.add(cb.equal(root.get("belongType"), belongTypeEnum.getCode()));
            predicateList.add(cb.equal(root.get("activityId"), activityId));
            predicateList.add(cb.equal(root.get("auditStatus"), ActivityGoodsAuditStatusEnum.AGREE.getCode()));

            if (StringUtils.hasLength(productName)) {
                predicateList.add(cb.like(root.get("productName"), "%" + productName + "%"));
            }

            Predicate[] p = new Predicate[predicateList.size()];
            return query.where(predicateList.toArray(p)).getRestriction();
        });

        return activityGoodsDOList.stream().map(ActivityGoodsDO::getProductId).distinct().collect(Collectors.toList());
    }

    @Override
    public Wrapper<PageData<MobileActivityGoodsPageResp>> pageActivityGoods(UserLoginCacheDTO loginUser, MobileActivityGoodsPageReq request) {
        Pageable page = PageRequest.of(request.getCurrent() - 1, request.getPageSize(), Sort.by("id"));

        Page<ActivityGoodsDO> pageList = activityGoodsRepository.findAll((Specification<ActivityGoodsDO>) (root, query, cb) -> {
            List<Predicate> predicateList = new ArrayList<>();
            predicateList.add(cb.equal(root.get("activityId"), request.getActivityId()));
            predicateList.add(cb.equal(root.get("belongType"), request.getBelongType()));
            predicateList.add(cb.equal(root.get("auditStatus"), ActivityGoodsAuditStatusEnum.AGREE.getCode()));

            Predicate[] p = new Predicate[predicateList.size()];
            return cb.and(predicateList.toArray(p));
        }, page);

        List<MobileActivityGoodsPageResp> resultList = pageList.stream().map(e -> {
            MobileActivityGoodsPageResp resp = new MobileActivityGoodsPageResp();
            resp.setId(e.getId());
            resp.setActivityId(e.getActivityId());
            resp.setBelongType(e.getBelongType());
            resp.setMemberId(e.getMemberId());
            resp.setMemberName(e.getMemberName());
            resp.setRoleId(e.getRoleId());
            resp.setRoleName(e.getRoleName());
            resp.setProductId(e.getProductId());
            resp.setSkuId(e.getSkuId());
            resp.setProductName(e.getProductName());
            resp.setType(e.getType());
            resp.setCategory(e.getCategory());
            resp.setBrand(e.getBrand());
            resp.setUnit(e.getUnit());
            resp.setProductImgUrl(e.getProductImgUrl());
            return resp;
        }).collect(Collectors.toList());

        return Wrapper.success(new PageData<>(pageList.getTotalElements(), resultList));
    }

    /**
     * @param goodsDO
     * @param setImg     是否只设置图片
     * @param groupPrice
     * @return
     */
    private SetmealGoodsResp buildSetmealGoodsResp(ActivityGoodsDO goodsDO, boolean setImg, BigDecimal groupPrice) {
        SetmealGoodsResp mainGoods = new SetmealGoodsResp();
        mainGoods.setProductImgUrl(goodsDO.getProductImgUrl());
        if (!setImg) {
            mainGoods.setPrice(goodsDO.getPrice());
            mainGoods.setBrand(goodsDO.getBrand());
            mainGoods.setCategory(goodsDO.getCategory());
            mainGoods.setType(goodsDO.getType());
            mainGoods.setUnit(goodsDO.getUnit());
            mainGoods.setProductId(goodsDO.getProductId());
            mainGoods.setProductName(goodsDO.getProductName());
            mainGoods.setSkuId(goodsDO.getSkuId());
            //套餐主商品默认数量1
            mainGoods.setNum(ServiceConfig.SET_MEAL_MAIN_GOODS_NUM);
            mainGoods.setGroupPrice(groupPrice);
        }
        return mainGoods;
    }

    private List<SetmealGoodsResp> convertSetmealGoodsRespList(List<SubsidiaryDto> subGoodsList, boolean setImg) {
        return subGoodsList.stream().map(o -> {
            SetmealGoodsResp sub = new SetmealGoodsResp();
            if (setImg) {
                sub.setProductImgUrl(o.getProductImgUrl());
            } else {
                BeanUtils.copyProperties(o, sub);
                sub.setProductName(o.getName());
                sub.setSkuId(o.getId());
            }
            return sub;
        }).collect(Collectors.toList());
    }

    /**
     * @param belongType
     * @param activityId
     * @param skuId
     * @param setImg     是否只查询图片
     * @return
     */
    private List<MobileSetmealGoodsGroupResp> getSetmealGoodsList(Integer belongType, Long activityId, Long skuId, boolean setImg) {
        ActivityGoodsDO goodsDO = activityGoodsRepository.findByBelongTypeAndActivityIdAndSkuId(belongType, activityId, skuId);
        if (goodsDO == null) {
            return null;
        }
        List<SubsidiaryDto> subsidiaryDtos = activityGoodsCacheService.selectSkuSetMealList(belongType, activityId, skuId, null);
        List<Integer> groupNoList = subsidiaryDtos.stream().map(SubsidiaryDto::getGroupNo).distinct().sorted().collect(Collectors.toList());
        //分组
        Map<Integer, List<SubsidiaryDto>> subGoodsMap = subsidiaryDtos.stream().collect(Collectors.groupingBy(SubsidiaryDto::getGroupNo));
        List<MobileSetmealGoodsGroupResp> respList = new ArrayList<>();
        for (Integer groupNo : groupNoList) {
            MobileSetmealGoodsGroupResp resp = new MobileSetmealGoodsGroupResp();
            resp.setGroupNo(groupNo);
            List<SubsidiaryDto> subGoodsList = subGoodsMap.get(groupNo);
            if (CollectionUtil.isEmpty(subGoodsList)) {
                continue;
            }
            double reduce = subGoodsList.stream().mapToDouble(o -> o.getNum().doubleValue()).sum();
            resp.setTotalNum(ServiceConfig.SET_MEAL_MAIN_GOODS_NUM.add(BigDecimal.valueOf(reduce)));
            List<SetmealGoodsResp> goodsList = new ArrayList<>();
            //团购价
            BigDecimal groupPrice = subGoodsList.get(0).getGroupPrice();
            //主商品
            SetmealGoodsResp mainGoods = buildSetmealGoodsResp(goodsDO, setImg, groupPrice);
            mainGoods.setGroupNo(groupNo);
            goodsList.add(mainGoods);
            //搭配商品
            goodsList.addAll(convertSetmealGoodsRespList(subGoodsList, setImg));
            //团购价
            resp.setTotalAmount(subGoodsList.get(0).getGroupPrice());
            resp.setGoodsList(goodsList);
            respList.add(resp);
        }
        return respList;
    }

    @Override
    public Wrapper<List<MobileSetmealGoodsGroupResp>> getSetmealImgList(UserLoginCacheDTO loginUser, MobileGoodsRelationTagReq request) {
        List<MobileSetmealGoodsGroupResp> respList = getSetmealGoodsList(request.getBelongType(), request.getActivityId(), request.getSkuId(), true);
        return Wrapper.success(respList);
    }

    @Override
    public Wrapper<List<MobileSetmealGoodsGroupResp>> getSetmealList(UserLoginCacheDTO loginUser, MobileGoodsRelationTagReq request) {
        List<MobileSetmealGoodsGroupResp> respList = getSetmealGoodsList(request.getBelongType(), request.getActivityId(), request.getSkuId(), false);
        if (CollectionUtil.isNotEmpty(respList)) {
            for (MobileSetmealGoodsGroupResp resp : respList) {
                //套餐商品总额
                double groupTotal = resp.getGoodsList().stream().mapToDouble(o -> o.getPrice().multiply(o.getNum()).doubleValue()).sum();
                SetmealGoodsResp mainGoods = resp.getGoodsList().get(0);
                if (resp.getGoodsList().size() > 1) {
                    BigDecimal subTotalAmount = BigDecimal.ZERO;
                    for (int i = 1; i < resp.getGoodsList().size(); i++) {
                        SetmealGoodsResp o = resp.getGoodsList().get(i);
                        BigDecimal skuAmount = o.getPrice().multiply(o.getNum());
                        //占比
                        BigDecimal ratio = skuAmount.divide(BigDecimal.valueOf(groupTotal), 3, BigDecimal.ROUND_HALF_UP);
                        o.setTotalAmount(o.getGroupPrice().multiply(ratio));
                        o.setDiscountAmount(skuAmount.subtract(o.getTotalAmount()));
                        subTotalAmount = subTotalAmount.add(o.getTotalAmount());
                    }
                    BigDecimal mainHandPrice = mainGoods.getGroupPrice().subtract(subTotalAmount);
                    mainGoods.setTotalAmount(mainHandPrice);
                    mainGoods.setDiscountAmount(mainGoods.getPrice().subtract(mainHandPrice));
                }
                resp.setDiscountAmount(BigDecimal.valueOf(groupTotal).subtract(mainGoods.getGroupPrice()));
            }
        }
        return Wrapper.success(respList);
    }

    @Override
    public Wrapper<List<MobileSetmealSubGoodsResp>> getSetmealSubGoodsList(UserLoginCacheDTO loginUser, MobileSetmealGoodsReq request) {
        List<MobileSetmealSubGoodsResp> respList = new ArrayList<>();
        ActivityGoodsDO activityGoodsDO = activityGoodsRepository.findByBelongTypeAndActivityIdAndSkuId(request.getBelongType(), request.getActivityId(), request.getMainSkuId());
        if (activityGoodsDO != null) {
            List<ActivityGoodsSubsidiaryDO> subsidiaryDOS = activityGoodsSubsidiaryRepository.findByActivityGoodsIdAndGroupNo(activityGoodsDO.getId(), request.getGroupNo());
            if (CollectionUtil.isNotEmpty(subsidiaryDOS)) {
                respList = subsidiaryDOS.stream().map(o -> {
                    MobileSetmealSubGoodsResp resp = new MobileSetmealSubGoodsResp();
                    resp.setProductId(o.getProductId());
                    resp.setSkuId(o.getSkuId());
                    resp.setProductName(o.getProductName());
                    resp.setProductImgUrl(o.getProductImgUrl());
                    resp.setNum(o.getNum());
                    return resp;
                }).collect(Collectors.toList());
            }
        }
        return Wrapper.success(respList);
    }
}
